package com.sunfeng.jksj.p25;

import com.sunfeng.TimeUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * @Author : 孙峰
 * @Description: CompletionService 的实现原理也是内部维护了一个阻塞队列，当任务执行结束就把任务的执行结果加入到阻塞队列中，
 * 不同的是 CompletionService 是把任务执行结果的 Future 对象加入到阻塞队列中
 *  API介绍
 *  Future submit(Callable task);
 *
 *  Future submit(Runnable task, V result);
 *
 *  Future take() throws InterruptedException
 *
 *  Future poll();
 *
 *  Future poll(long timeout, TimeUnit unit) throws InterruptedException;
 *
 * @Date : 2022/3/3  8:56
 */

@Slf4j(topic = "c.Demo02")
public class Demo02 {
    public static void main(String[] args) {

        ExecutorService executorService = Executors.newFixedThreadPool(3);
        // 使用默认的无界队列完成
        ExecutorCompletionService<Integer> ecs = new ExecutorCompletionService<>(executorService);

//        使用自定义有界阻塞队列完成
     //   ExecutorCompletionService<Object> completionService = new ExecutorCompletionService<>(executorService, new ArrayBlockingQueue<>(10));
        log.info("开始获取价格！！！！！");
       ecs.submit(() -> {
            TimeUtils.sleep(4);
            return 100;
        });
        ecs.submit(() -> {
            TimeUtils.sleep(3);
            return 30;
        });
        ecs.submit(() -> {
            TimeUtils.sleep(2);
            return 20;
        });
        for (int i = 0; i < 3; i++) {
            try {
                Integer integer = ecs.take().get();
                executorService.execute(()->{
                 log.info("最先获取的价格Wie:"+integer);
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}
